/**
 * bootstrap 的拓展
 * @version   1.0 2016/7/7
 * @author    黄坚：huangjian@sunmnet.com
 * @since     jdk版本：jdk1.7
 */

/**
 * 屏幕锁定或解锁
 * @param flag 锁定/解锁
 */
sUtils.lockScreen = function (flag) {
    if (flag) {
        $('.page-content-area').ace_ajax('startLoading');
    } else {
        $('.page-content-area').ace_ajax('stopLoading', true);
    }
};

/**
 * select2 枚举下拉
 * @param options
 */
sUtils.select2Enum = function (options) {
    /**
     * select2下拉默认配置
     */
    var select2EnumDef = {
        selector: 'select',
        enums: [],					//枚举对象数组，有enums，则不需要enumKey和map
        enumKey: null,			//枚举关键字'表名-字段名'
        enumMap: null,				//已经查出来的枚举map对象

        /* **************必填分割线，上面必填，下面可选 *************************************/
        width: '200px',
        defVal: null,				//枚举的默认显示值，未实现
        valueField: 'enumCode',		//select的value值字段
        textField: 'enumValue',		//的显示值字段
        textMapField: 'enumMapValue',		//的显示值字段
        useMapTextField: false,	    //是否使用枚举映射值
        select2Option: {},
        addAll: false				//是否添加全部选项

    };

    options = $.extend({}, select2EnumDef, options);

    if (options.enums == null) {
        if (options.enumKey != null && options.enumMap != null) {
            options.enums = options.enumMap.get(options.enumKey);
        } else {
            console.log(options.selector + ' enumKey和enumMap必须同时存在');
        }
    }

    var arrs = options.enums.concat();

    if (options.addAll) { //添加全部到枚举数组中
        arrs.splice(0, 0,
            {enumCode: '', enumValue: '全部'});
    }

    var val = options.valueField;
    var text = options.textField;
    if (options.useMapTextField == true) {
        text = options.textMapField;
    }
    var defSelect = 0;
    $(options.selector).html('');
    $.each(arrs, function (index, value) {
        if (value['defStatus'] == 1) {
            defSelect = value['enumCode'];
        }
        $(options.selector).append('<option value="'
            + value[val] + '">'
            + value[text]
            + '</option>');
    });

    $(options.selector).select2(options.select2Option);
    $(options.selector).select2('val', defSelect);
    if (options.addAll) { //默认初始化全部
        $(options.selector).select2('val', '');
    }


};


/**
 * 重置表单验证
 * @param selector
 */
sUtils.validResetForm = function (selector) {
    $(selector).validate().resetForm();
    $(selector).find('.form-group').removeClass('has-error').addClass('has-info');
};

/**
 *    给表单添加验证
 * @param selector
 * @param rules
 * @param message
 */
sUtils.validClass = function (selector, rules, message) {
    $(selector).validate({
        errorElement: 'div',
        errorClass: 'help-block',
        focusInvalid: false,
        ignore: '',
        rules: rules,
        message: message,
        /*
         rules: {
         cronExpression: {
         required: true
         },
         name: {
         required: true
         },
         webUrl: {
         required: true,
         }
         },
         */

        /*
         messages: {
         webUrl: {
         required: '网站地址不能为空',
         url: '请输入正确的url'
         },
         name: {
         required: '网站名称不能为空'
         },
         cronExpression: 'CRON表达式不能为空'
         },*/


        highlight: function (e) {
            $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
        },

        success: function (e) {
            $(e).closest('.form-group').removeClass('has-error').addClass('has-info');
            $(e).remove();
        },

        errorPlacement: function (error, element) {
            if (element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                var controls = element.closest('div[class*="col-"]');
                if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
            }
            else if (element.is('.select2')) {
                error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
            }
            else if (element.is('.chosen-select')) {
                error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
            }
            else {
                var outerHTML = error.prop("outerHTML");
                if ($(outerHTML).text()) {
                    var str = '<div class="col-sm-9 col-sm-push-3">' + outerHTML + '</div>';
                    $(str).insertAfter(element.parent());
                }
            }
        },

        submitHandler: function (form) {
        },
        invalidHandler: function (form) {
        }
    });
};

/**
 * 大数据项目公共方法添加
 * @version   1.0 2016/7/8
 * @author    黄坚：huangjian@sunmnet.com
 * @since     jdk版本：jdk1.7
 */


/**
 * 加载表单数据
 * @param formId 表单id
 * @param datas        加载的数据
 */
sUtils.setFrom = function (formId, datas) {
    var obj = $(formId);
    $.each(datas, function (key, val) {
        var $oinput = obj.find('input[name="' + key + '"]');
        if ($oinput.attr('type') == 'radio' || $oinput.attr('type') == 'checkbox') {
            $oinput.each(function () {
                if ($(this).val() == val)
                    $(this).attr('checked', 'checked');
            });
        } else {
            obj.find('[name="' + key + '"]').val(val);
        }
    });
};


/**
 * 清除表单数据
 * @param formId 表单id
 */
sUtils.cleanFrom = function (formId) {
    $.each($(formId).find('input'), function () {
        $(this).val('');
    });
};

/**
 * 弹出提示信息
 */
sUtils.showMsg = function (msg) {
    layer.alert(msg, {icon: 5, title: '提示'});
};

/**
 * 弹出提示成功信息
 */
sUtils.showSuccessMsg = function (msg) {
    layer.alert(msg, {icon: 1, title: '提示'});
};

/**
 * 弹出提示失败信息
 */
sUtils.showFailMsg = function (msg) {
    layer.alert(msg, {icon: 2, title: '提示'});
};

/**
 * 默认提示弹窗
 */
sUtils.alert = function (msg) {
    if (msg.indexOf('成功') != -1) {
        layer.alert(msg, {icon: 1, title: '提示'});
    } else if (msg.indexOf('失败') != -1) {
        layer.alert(msg, {icon: 2, title: '提示'});
    } else {
        layer.alert(msg, {icon: 5, title: '提示'});
    }
};


/**
 * 表单验证
 * @param selector
 * @param rules
 * @param message
 */
sUtils.formValidClass = function (selector, rules, message) {
    $(selector).validate({
        errorElement: 'div',
        errorClass: 'help-block',
        focusInvalid: false,
        ignore: '',
        rules: rules,
        message: message,

        highlight: function (e) {
            $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
        },

        success: function (e) {
            $(e).closest('.form-group').removeClass('has-error').addClass('has-info');
            $(e).remove();
        },

        errorPlacement: function (error, element) {
            if (element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                var controls = element.closest('div[class*="col-"]');
                if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
            }
            else if (element.is('.select2')) {
                error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
            }
            else if (element.is('.chosen-select')) {
                error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
            }
            else {
                //var str = '<div class="col-sm-9 col-sm-push-3">' + error.prop("outerHTML") + '</div>';
                //$(str).insertAfter(element.parent());
                // 修改验证错误提示信息显示的样式
                error.insertAfter(element);
            }
        },
        submitHandler: function (form) {
        },
        invalidHandler: function (form) {
        }
    });
};

sUtils.checkIpValid = function (ip) {
    var re = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    return re.test(ip);
};

/**
 * 菜单拼接方法
 * @type {{createMenuHtml, createMenuLi, loadMenu, loadMenu4TreeData, loadMenu4ArrData, loadMenu4AccountId, version}}
 */
var menuUtils = function () {

    /** 获取菜单的请求地址  **/
    var url = path + '/action/security/menu/findAccountHadMenus';

    /**
     * 获取默认的菜单数据
     * @param selector
     * @param accountId
     */
    function getArrDatas(accountId) {


        var menus = stroage.getSessionItem(CURRENT_USER_MENUS);

        if (menus) {
            slog.info('页面缓存取菜单数据');
            //tree = sUtils.treeGridDataConvert(menus);
        } else {
            slog.info('后台取菜单数据');
            var data = sPost.getPostResponse(url, {accountId: accountId});
            if (data.success) {
                //tree = sUtils.treeGridDataConvert(data.obj);
                menus = data.obj;
            } else {
                slog.error(data.msg);
            }
        }
        return menus;
    }

    return {


        /**
         * 拼接首页内容
         * @param data
         * @returns {string}
         */
        createMenuHtml: function (data) {
            var str = '';
            var index = null;
            //拼接首页
            index = data[0];
            str += '<li class="">' +
                '<a data-url="page/home" href="#page/home">' +
                '<i class="menu-icon fa fa-tachometer"></i>' +
                '<span class="menu-text"> 首页</span>' +
                '</a>' +
                '<b class="arrow"></b>' +
                '</li>';

            //拼接首页的孩子
            str += menuUtils.createMenuLi(index.children);
            str += '';
            return str;
        },

        /**
         * 菜单内容拼接
         * @param dataArr
         * @returns {string}
         */
        createMenuLi: function (dataArr) {
            if (!dataArr) {
                return '';
            }
//		slog.log(dataArr);
            var flag = false;
            var urlFlag = false;
            var len = dataArr.length;
            var data = null;
            var line = '\r\n';
            var str = '';
            var dataUrl = '';
            for (var i = 0; i < len; i++) {
                data = dataArr[i];
                if (data.children) {
                    flag = true;
                } else {
                    flag = false;
                }
                dataUrl = data['url'];
                if ((dataUrl == null || dataUrl == "") && flag == false) {
                    urlFlag = true;
                } else {
                    urlFlag = false;
                }
                str += '<li class="' + (flag ? 'dropdown-toggle' : '') + '">' + line;
                str += '<a class="' + (flag ? 'dropdown-toggle' : '') + '"';
                str += 'id="' + (urlFlag ? 'menuFontColor' : '') + '"' + line;
                str += 'openType="' + data['openType'] + '"' + line;
                str += 'data-url="page/' + (flag ? '' : data['url']) + '"' + line;
                str += 'href="#page/' + (flag ? '' : data['url']) + '" >';
                str += '<i class="' + (flag ? 'menu-icon fa fa-desktop' : 'menu-icon fa fa-caret-right') + '"></i>' + line;
                str += '<span class="menu-text"> ' + data['name'] + ' </span>' + line;
                str += '<b class="' + (flag ? 'arrow fa fa-angle-down' : 'arrow') + '"></b>' + line;
                str += '</a>' + line;
                if (flag) {
                    str += '<b class="arrow"></b>';
                    str += '<ul class="submenu">' + line;
                    str += menuUtils.createMenuLi(data.children);
                    str += '</ul>' + line;
                }
                str += '</li>' + line;
            }
            return str;
        },

        /**
         * 加载菜单
         * @param selector jquery选择器
         * @param options {treeData: [], arrData: [] , accountId: 1}
         */
        loadMenu: function (selector, options) {
            if (sUtils.notNull(options['accountId'])) {
                options['arrData'] = getArrDatas(options['accountId']);
                menuUtils.loadMenu4AccountId(selector, options['accountId']);
            } else if (sUtils.notNull(options['arrData'])) {
                menuUtils.loadMenu4ArrData(selector, options['arrData']);
            } else if (sUtils.notNull(options['treeData'])) {
                menuUtils.loadMenu4TreeData(selector, options['treeData']);
            } else {
                console.warn('加载首页菜单数据异常');
                console.error(options);
            }
        },

        /**
         *  使用树形结构数据加载菜单
         * @param selector
         * @param treeData
         */
        loadMenu4TreeData: function (selector, treeData) {
            var html = menuUtils.createMenuHtml(treeData);
            $(selector).html(html);
        },

        /**
         *    使用数组结构数据加载菜单
         * @param selector
         * @param arrData
         */
        loadMenu4ArrData: function (selector, arrData) {
            var treeData = sUtils.treeGridDataConvert(arrData);
            menuUtils.loadMenu4TreeData(selector, treeData);
        },

        /**
         * 使用用户id加载菜单
         * @param selector
         * @param accountId
         */
        loadMenu4AccountId: function (selector, accountId) {
            var arrData = getArrDatas(accountId);
            menuUtils.loadMenu4ArrData(selector, arrData);
        },

        version: function () {
        }
    }

}();

sPost.ajaxPut = function (url, params, successFun, failFun, alwaysFun, async) {
    if (sUtils.isNull(params)) {
        params = {};
    }
    params._method = 'PUT';
    sPost.ajax(url, params, successFun, failFun, alwaysFun, 'POST', async);
};